<?php


namespace app\crontab\controller\once;


use app\common\lib\RespCode;
use app\crontab\model\House;
use custom\Log;
use custom\Mongo;
use custom\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

/**
 * 补救房源的拍卖id
 * Class RemedyHouseAuctionId
 * @package app\crontab\controller
 */
class RemedyHouseAuctionId extends Command {

    protected function configure() {
        $this->setName('RemedyHouseAuctionId');
    }

    protected function execute(Input $input, Output $output) {
        echo "starting\n";
        self::ali();
        self::jd();
    }

    public static function ali() {
        $mongo = Mongo::getInstance();
        $redisModel = Redis::getInstance();
        $suc = 0;
        $total = 0;
        $errNum = 0;//错误次数
        while (true) {
            try {
                $_id = $redisModel->get('house_ali_log');
                if ($_id === false) break;
                //历史id+1
                $_id = (int)$_id + 1;
                $cursor = $mongo->select('house_ali_log', ['_id' => $_id], ['limit' => 1]);
                if (empty($cursor)) break;
                $data = (array)$cursor[0];
                $total++;
                //验证参数
                House::checkParams($data, ['house_id', 'title', '_id']);
                //数据处理
                $has_house_auction = db("house_auction")->where("source_id", $data['house_id'])->find();
                $has_house = db("house")->where('sn', md5($data['title']))->find();
                Db::startTrans();
                //拍卖、房源同步数据
                if ($has_house_auction && $has_house) self::handleSyncData($data, $has_house_auction, $has_house);
                //处理完毕
                Db::commit();
                $redisModel->set('house_ali_log', $data['_id']);
                $suc++;
            } catch (Exception $e) {
                Db::rollback();
                Db::close();
                $err = "id:{$_id}|" . $e->getMessage() . ' (' . $e->getCode() . '), ' . $e->getFile() . ' (' . $e->getLine() . ')' . "\n" . $e->getTraceAsString() . "\r\n\r\n";
                if ($errNum >= 3) {
                    break;
                }
                $errNum++;
                //跳过这条错误房源
                $redisModel->set('house_ali_log', $data['_id'] + 1);
                Log::write($err, "Ali_houseErr.log");
                continue;
            }
        }
        echo 'total->' . $total . PHP_EOL;
        echo 'suc->' . $suc . PHP_EOL;
        echo "end" . PHP_EOL;
        Log::write("total->$total;suc->$suc", "Ali_houseResult.log");
    }

    public static function jd() {
        $mongo = Mongo::getInstance();
        $redisModel = Redis::getInstance();
        $suc = 0;
        $total = 0;
        $errNum = 0;//错误次数
        while (true) {
            try {
                $_id = $redisModel->get('house_jd_log');
                if ($_id === false) break;
                //历史id+1
                $_id = (int)$_id + 1;
                $cursor = $mongo->select('house_jd_log', ['_id' => $_id], ['limit' => 1]);
                if (empty($cursor)) break;
                $data = (array)$cursor[0];
                $total++;
                //验证参数
                House::checkParams($data, ['house_id', 'title', '_id']);
                //数据处理
                $has_house_auction = db("house_auction")->where("source_id", $data['house_id'])->find();
                $has_house = db("house")->where('sn', md5($data['title']))->find();
                Db::startTrans();
                //拍卖、房源同步数据
                if ($has_house_auction && $has_house) self::handleSyncData($data, $has_house_auction, $has_house);
                //处理完毕
                Db::commit();
                $redisModel->set('house_jd_log', $data['_id']);
                $suc++;
            } catch (Exception $e) {
                Db::rollback();
                Db::close();
                $err = "id:{$_id}|" . $e->getMessage() . ' (' . $e->getCode() . '), ' . $e->getFile() . ' (' . $e->getLine() . ')' . "\n" . $e->getTraceAsString() . "\r\n\r\n";
                if ($errNum >= 3) {
                    break;
                }
                $errNum++;
                //跳过这条错误房源
                $redisModel->set('house_jd_log', $data['_id'] + 1);
                Log::write($err, "Jd_houseErr.log");
                continue;
            }
        }
        echo 'total->' . $total . PHP_EOL;
        echo 'suc->' . $suc . PHP_EOL;
        echo "end" . PHP_EOL;
        Log::write("total->$total;suc->$suc", "Jd_houseResult.log");
    }

    public static function handleSyncData($params, $has_house_auction, $house_data) {
        $syncData = $params;
        unset($syncData['_id']);
        unset($syncData['title']);
        unset($syncData['house_id']);
        unset($syncData['itime']);
        if (isset($syncData['id'])) unset($syncData['id']);
        //转换金额
        $syncData = price_arr_deal($syncData, 1);

        $houseUpdate = [];
        //如果房源market_price为空，更新为拍卖的market_price
        if (empty($house_data['market_price']) && isset($syncData['market_price'])) {
            $houseUpdate['market_price'] = $syncData['market_price'];
        }

        $auc = db("house_auction")->where("source_id", $params['house_id'])->field('id,source_url')->find();
        $houseUpdate['auction_id'] = $auc['id'];
        $houseUpdate['source_url'] = $auc['source_url'];
        if (db("house")->where("title", $params['title'])->update($houseUpdate) === false)
            throw new Exception("更新house错误", RespCode::PARAMS_ERR);
    }
}
